// pages/detail/detail.js
import request from '../../utils/config.js';
import util from '../../utils/util.js';
const app = getApp();
Page({
  data: {
    currentNum: 0,
    periodDaysColor: '#58b5e1',
    showAble: true,
    caseDetail: {},
    enforceCurrInfos: {},
    enforceStep: {},
    roles: [],//用户权限
    otherInput: [],
    branchList: [],
    nextStepIndex: 'none',
    configType: true,
    isFavor: "Y",
    imgSign: '',
    array: ['法律文书生效测试结束', '美国', '中国', '巴西', '日本'],
    isloading: false,
    enforceStepList: [],
    breakReasons: [],
    breakReasonsIndex: 'none',
    breakReasonsDesc: '',
    breakTypes: [{
      id:'1',
      breakType:"自动恢复"
    }, {
      id: '2',
      breakType: "长期生效"
    }],
    breakTypeIndex: 0,
    ROLE_BreakForEver: false,
    modalForInput: false,
    modalClose: false,
    enforceStepRecordWithBLOBs: [],
    txtTypeList: [{
      label: '判决书',
      key: '1',
    }, {
      label: '调解书',
      key: '2',
    }, {
      label: '仲裁书',
      key: '3',
    }, {
      label: '支付令',
      key: '4',
    }],
    defaultTxtType: 0,
    txtDate: "",
    editOrSave: "编辑",
    userCanseeType:true,
    showEdit:false,
    edit_value:"",
    editId:"",
    newDateTime: new Date().getTime(),
    tab3Flag:false,
    showBranch: false,
    branchItems: [],
    branchNextSteptId: "",
    onChangeData: {},
    items: [
      { value: '选择', slt: 'Y', checked: 'true' },
      { value: '手工输入', slt: 'N', }
    ],
    userVisualResult: true,
    subZindex: 10,
    animationM: {},
    animationS: {},
    stepDesc:"",
    caseId: "",
    showModel: false,
    showHomeBtn: false,
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onLoad: function (options) {
    if (options.caseId) {
      this.setData({
        caseId: options.caseId,
        showHomeBtn: true,
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    if (!wx.getStorageSync('token')) {
      //未登录
      wx.showModal({
        title: '未登录',
        content: '请先登录系统',
        confirmText: '前去登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
      return
    }
    //判断案件进入的场景（列表进入、推送消息进入）
    if (app.globalData.userInfo && !this.data.caseId) {//列表进入
      this.setData({
        caseDetail: app.globalData.caseDetailData,
        roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_StepRecordManage'),
        ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
      });
      this.get_enforceCurrInfos()
    } else {//消息推送
      app.globalData.caseDetailData ={};
      let _that = this;
      if (!app.globalData.userInfo) {//判断是否登录过
        app.getAuthUserInfo((res) => {
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          app.globalData.encryptedData = res.encryptedData;
          app.globalData.iv = res.iv;
          _that.getOpenid(_that);
        }, (res) => {
          _that.setData({
            showModel: true
          })
        });
      } else {//已登录
        //先还原赋值
        app.globalData.caseDetailData.caseId = this.data.caseId;
        this.setData({
          caseDetail: app.globalData.caseDetailData,
          roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_StepRecordManage'),
          ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
        });
        this.get_enforceCurrInfos()
      }
    }
  },


  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    that.getOpenid(that);
  },

  //点击返回首页组件回调
  _goHomeBtn: function (e) {
    wx.setStorageSync("flagName", "enforce");
    wx.redirectTo({
      url: '../syIndex/syIndex?flagName=enforce'
    })
  },

  //获取openid
  getOpenid: (_that) => {
    app.getGlobalOpenid(function (token) {
      if (token) {
        //开始校验看token值
        _that.checkToken();
      } else {
        wx.hideLoading();
        //未登录
        wx.showModal({
          title: '未登录',
          content: '请先登录系统',
          confirmText: '前去登录',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
      }
    });
  },

  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
        wx.showModal({
          title: '对不起',
          content: '您的权限不足',
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }

      //校验上次记住的部门权限是否还存在
      if (jurisdiction.indexOf(roleQuanxian) < 0) {
        wx.showModal({
          title: '对不起',
          content: "您的" + department + "权限不足",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      app.globalData.caseDetailData.caseId = _that.data.caseId;
      _that.setData({
        caseDetail: app.globalData.caseDetailData,
        roles_quanxian: app.globalData.loginUserInfo.roles.includes('ROLE_StepRecordManage'),
        ROLE_BreakForEver: app.globalData.loginUserInfo.roles.includes('ROLE_BreakForEver')
      });
      _that.get_enforceCurrInfos()
    }, function (res) {
      //登录超时
      wx.showModal({
        title: '登录超时',
        content: '点击确定重新登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.toast = this.selectComponent("#toast");
    this.homeBtn = this.selectComponent("#homeBtn");
  },

  // 获取caseLi高度
  getRect: function () {
    let _this = this;
    wx.createSelectorQuery().select('#caseLiId').boundingClientRect(function (rect) {
      rect.id      // 节点的ID
      rect.height  // 节点的高度
      console.log(rect.height)
      _this.showCaseLi(rect.height)
    }).exec()
  },
  showCaseLi: function (height) {
    console.log(height)
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.height(height).step()

    var animation2 = wx.createAnimation({
      duration: 200,
      timingFunction: "ease",
      delay: 0
    })
    this.animation2 = animation2
    animation2.height(0).step()

    this.setData({
      animationM: animation.export(),
      animationS: animation2.export(),
    })
  },
  toTop: function () {
    this.animation.height(0).step()
    this.animation2.height(34).step()
    this.setData({
      animationM: this.animation.export(),
      animationS: this.animation2.export()
    })
  },

  // 步骤描述
  change_trackDesc: function (e) {
    console.log(e)
    this.setData({
      stepDesc: e.detail
    })
  },

  
  get_enforceCurrInfos() {
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('get', "enforceCurrInfos/" + app.globalData.caseDetailData.caseId, {}, (res) => {
      if (res.code == '00') {
        let enforceCurrInfos = JSON.parse(res.body)
        _this.setData({
          stepDesc: enforceCurrInfos.stepDesc
        })
        console.log("enforceCurrInfos=", enforceCurrInfos)
        let imgSign = '';
        let periodDaysColor = '';
        if (enforceCurrInfos.status === '2') {
          imgSign = "state2.png";
          periodDaysColor = "#a1a1a1";
        } else if (enforceCurrInfos.status === '3') {
          imgSign = "state5.png";
          periodDaysColor = '#1aac19'
        } else if (enforceCurrInfos.status === '4') {
          imgSign = "state4.png";
          periodDaysColor = '#1aac19'
        } else if (enforceCurrInfos.status === '1') {
          imgSign = enforceCurrInfos.expireSign == '1' ? 'state3.png' : 'state1.png';
          periodDaysColor = enforceCurrInfos.expireSign == '1' ? '#ff6161' : '#58b5e1';
        }
        //为了解决从消息场景进入小程序要对全局赋值
        app.globalData.caseDetailData.debtorName = enforceCurrInfos.debtorName;//被告
        app.globalData.caseDetailData.creditorName = enforceCurrInfos.creditorName;//被告

        _this.setData({
          enforceCurrInfos: enforceCurrInfos,
          periodDaysColor: periodDaysColor,
          isFavor: enforceCurrInfos.isFavor,
          imgSign: imgSign,
          caseDetail: app.globalData.caseDetailData
        });
        if (enforceCurrInfos.stepId) {
          request.requestMisApi('get', "enforceStepConfigs/" + enforceCurrInfos.stepId, {}, (res) => {
            let enforceStep = JSON.parse(res.body)
            wx.hideLoading()
            if (res.code == '00') {
              let enforceStep = JSON.parse(res.body), otherInput = [], branchList = [];
              console.log("enforceStep=", enforceStep)
              if (enforceStep.isBranch === 'N' && enforceStep.inputJson != '[]') {
                JSON.parse(enforceStep.inputJson).forEach(function (item) {
                  if (item.type === 'date') {
                    // item.value = util.timetrans(new Date(), 'day');
                    item.value = '';
                  } else if (item.type === 'dateTime') {
                    // item.value_date = util.timetrans(new Date(), 'day');
                    // item.value_time = util.timetrans(new Date(), 'timeHM');
                    item.value_date = '';
                    item.value_time = '';
                  }
                  otherInput.push(item)
                })
              }
              if (enforceStep.isBranch === 'Y' && enforceStep.branchJson != '[]') {
                JSON.parse(enforceStep.branchJson).forEach(function (item) {
                  item.branchDesc = item.branchName + " -> " + item.nextStep.split('-')[1]
                  branchList.push(item)
                })
              }
              _this.setData({
                enforceStep: enforceStep, otherInput: otherInput, branchList: branchList
              });
              _this.get_enforceStep()
            }
          }, (res) => {
            console.log("接口错误=", res)
          });
        } else {
          wx.hideLoading()
          _this.setData({
            enforceStep: {
              isBranch: 'N',
              inputJson: '[]',
              branchJson: '[]',
            }, otherInput: [], branchList: []
          });
          _this.get_enforceStep()
        }
      }
    }, (res) => {
      console.log("接口错误=", res)
    });
  },
  get_enforceStep() {
    let _this = this;
    if (this.data.enforceStepList.length != 0) {
      let nextStepIndex = 'none';
      this.data.enforceStepList.forEach(function (e, index) {
        if (e.stepId == _this.data.enforceStep.nextStepId && _this.data.enforceStep.isBranch === 'N') {
          nextStepIndex = index;
        }
      })
      this.setData({
        // nextStepIndex: nextStepIndex
      });
      this.get_breakReasons()
      return;
    }
    request.requestMisApi('get', "enforceStepConfigs/alls", {}, (res) => {
      if (res.code == '00') {
        let nextStepIndex = 'none';
        JSON.parse(res.body).forEach(function (e, index) {
          if (e.stepId == _this.data.enforceStep.nextStepId && _this.data.enforceStep.isBranch === 'N') {
            nextStepIndex = index;
          }
        })
        _this.setData({
          enforceStepList: JSON.parse(res.body), 
          // nextStepIndex: nextStepIndex
        });
        console.log(JSON.parse(res.body))
      }
      _this.get_breakReasons()
    }, (res) => {
      console.log("接口错误=", res)
    });
  },
  get_breakReasons: function () {
    if (this.data.breakReasons.length > 0) {
      //return;  如果中断原因已存在也要获取
    }
    let _this = this;
    request.requestMisApi('get', "breakReasons", { status: '0' }, (res) => {
      console.log(res)
      _this.setData({
        breakReasons: res,
      });
      if (_this.data.tab3Flag){
        _this.tab3()
      }
    }, (res) => {
      console.log("接口错误=", res)
    });
  },
  // 收藏取消
  collect: function () {
    if (this.data.isloading) {
      return
    }
    this.setData({
      isloading: true
    });
    let _this = this;
    if (this.data.isFavor == "Y") {
      request.requestMisApi('get', "flyWorkPlace/unfavorCases/" + app.globalData.caseDetailData.caseId, {}, (res) => {
        console.log(res)
        if (res.code == '00') {
          _this.setData({
            isFavor: "N",
            isloading: false
          });
        }
      }, (res) => {
        console.log("接口错误=", res)
      });
    } else {
      request.requestMisApi('get', "flyWorkPlace/favorCases/" + app.globalData.caseDetailData.caseId, {}, (res) => {
        console.log(res)
        if (res.code == '00') {
          _this.setData({
            isFavor: "Y",
            isloading: false
          });
        }
      }, (res) => {
        console.log("接口错误=", res)
      });
    }
  },

  //用户可见操作
  userCanseeChange: function(e){
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      userCanseeType: e.detail.value
    })
    if (e.detail.value) {
      this.setData({
        userVisualResult: true
      })
    } else {
      this.setData({
        userVisualResult: false
      })
    }
  },

  // 展开合并 文件列表
  toggle: function (e) {
    let index = e.currentTarget.dataset.index;
    let fileLength = e.currentTarget.dataset.filelength
    let enforceStepList = this.data.enforceStepRecordWithBLOBs;
    if (fileLength > 0) {
      if (enforceStepList[index].openFile) {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
      } else {
        enforceStepList.forEach(function (e) {
          e.openFile = false;
        });
        enforceStepList[index].openFile = true;
      }
      this.setData({
        enforceStepRecordWithBLOBs: enforceStepList
      });
    }
  },

  //点击下载文件
  dowmloadFile: function (e) {
    let fileurl = e.currentTarget.dataset.url;
    let docName = e.currentTarget.dataset.name;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl)
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        console.log("读取文件失败=", res);
      }
    })
  },


  //步骤分支选择
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    let nextStepId = e.detail.value.split('-')[0];
    let returnData = this.getSteptDataBySteptId(nextStepId, this);
    console.log("returnData====", returnData)
    if (returnData.isBranch == "Y") {
      let list = JSON.parse(returnData.branchJson);
      list.forEach(function (e) {
        e.text = e.nextStep.split("-")[1]
      });
      //弹框显示分支
      this.setData({
        branchItems: list,
      });
    } else {
      this.setData({
        branchNextSteptId: returnData.stepId
      });
      // this.subData(this.data.onChangeData)
    }
  },
  radioHandChange: function(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    if (e.detail.value == '选择') {
      this.setData({
        configType: true
      })
    } else if (e.detail.value == '手工输入') {
      this.setData({
        configType: false
      })
    }
  },

  //根据steptId获取对应的stept值
  getSteptDataBySteptId: (steptId, _this) => {
    let list = _this.data.enforceStepList;
    let returndata = "";
    for (let i = 0; i < list.length; i++) {
      if (list[i].stepId == steptId) {
        returndata = list[i];
      }
    }
    return returndata;
  },

  //取消分支显示
  cancleBranch: function () {
    this.setData({
      showBranch: false
    });
  },

  //分支弹框确定
  confirmBranch: function () {
    console.log("this.data.onChangeData=", this.data.onChangeData)
    this.subData(this.data.onChangeData)
  },

  //点击完成提交相关数据
  subData: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    let _this = this, sendData = {
      caseId: app.globalData.caseDetailData.caseId
    }, recordText = '', content = [], other = [];
    let { otherInput, enforceStepList, enforceStep, branchList } = this.data;
    if (this.data.stepDesc) {
      sendData.stepDesc = this.data.stepDesc;
      recordText = this.data.stepDesc
    } else {
      wx.showToast({ title: '描述不能为空', icon: 'none', duration: 800 });
      return;
    }
    if (enforceStep.isBranch === "N") {
      sendData.userVisual = e.detail.value.userVisual ? "Y" : "N";
    } else {
      sendData.userVisual = 'N'
    }
    if (sendData.userVisual == "Y") {
      sendData.delaySend = e.detail.value.delaySend ? "Y" : "N";
    }
    console.log(this.data.otherInput)
    for (let i = 0; i < otherInput.length; i++) {
      if (otherInput[i].value || (otherInput[i].value_date && otherInput[i].value_time)) {
        if (otherInput[i].type === 'dateTime') {
          other.push(otherInput[i].text + '：' + otherInput[i].value_date + ' ' + otherInput[i].value_time + ":00")
          content.push({
            text: otherInput[i].text,
            type: otherInput[i].type,
            value: otherInput[i].value_date + ' ' + otherInput[i].value_time + ":00"
          })
        } else {
          other.push(otherInput[i].text + '：' + otherInput[i].value)
          content.push(otherInput[i])
        }
      } else {
        //wx.showToast({ title: otherInput[i].text + '不能为空', icon: 'none', duration: 800 });
        //return;
      }
    }
    if (other.length > 0) {
      sendData.recordText = recordText + ' ' + other.toString().replace(/,/g, '，')
    } else {
      sendData.recordText = recordText + ' '
    }
    sendData.content = JSON.stringify(content);
    if (!this.data.configType) {
      if (!e.detail.value.other_nextStep) {
        wx.showToast({ title: '请正确输入下一个步骤', icon: 'none', duration: 800 });
        return;
      }
      // if (!/^\d+$/.test(e.detail.value.other_periodDays)) {
      //   wx.showToast({ title: '请正确输入期限天数', icon: 'none', duration: 800 });
      //   return;
      // }
      // if (Number(e.detail.value.other_periodDays) > 5) {
      //   wx.showToast({ title: '期限天数不得大于5', icon: 'none', duration: 800 });
      //   return;
      // }
      sendData.stepName = e.detail.value.other_nextStep;
      sendData.periodDays = '5';
    } else {
      if (this.data.nextStepIndex !== 'none') {
        if (this.data.branchNextSteptId) {
          sendData.nextStepId = this.data.branchNextSteptId;
        } else {
          if (enforceStep.isBranch === "Y") {
            sendData.nextStepId = branchList[this.data.nextStepIndex].nextStep.split('-')[0];
          } else {
            sendData.nextStepId = enforceStepList[this.data.nextStepIndex].stepId;
          }
        }
      } else {
        if (enforceStep.nextStepId || enforceStep.isBranch === "Y" || !enforceStep.stepId) {
          wx.showToast({ title: '请选择下一步骤', icon: 'none', duration: 800 });
          return;
        }
      }
    }
    sendData.stepId = enforceStep.stepId;
    console.log(sendData);
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('post', "enforceStepRecords", sendData, (res) => {
      console.log(res);
      wx.hideLoading()
      if (res.code == '00') {
        // _this.get_enforceCurrInfos()
        // wx.showToast({ title: res.msg, icon: 'success' })
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
        if (app.globalData.listRefresh.SY.tabtype == 'dynamics') {
          app.globalData.listRefresh.SY = {
            refresh: true,
          }
        }
        setTimeout(function () {
          wx.navigateBack({});
        }, 1500);
      } else {
        wx.showToast({ title: res.msg, icon: 'none' })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("接口错误=", res)
    });
  },
  delaySendChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      delaySend: e.detail.value
    })
  },

  formSubmit: function (e) {
    this.setData({
      onChangeData: e,
      branchNextSteptId: ""
    });
    let { otherInput, enforceStepList, enforceStep, branchList } = this.data;
    if (!this.data.configType) {
      this.subData(e)
    } else {
      //先判断有没有分支
      if (this.data.nextStepIndex !== 'none') {
        if (!this.data.stepDesc) {
          wx.showToast({ title: '描述不能为空', icon: 'none', duration: 800 });
          return;
        }
        if (enforceStep.isBranch === "N") {
          let tempNextStepData = enforceStepList[this.data.nextStepIndex];
          if (tempNextStepData.isBranch == "Y") {
            // branchItems
            let branchList = JSON.parse(tempNextStepData.branchJson);
            branchList.forEach(function (e) {
              e.text = e.nextStep.split("-")[1]
            });
            //弹框显示分支
            this.setData({
              branchItems: branchList,
              showBranch: true
            });
          } else {
            this.subData(e)
          }
        } else {
          this.subData(e)
        }
      } else {
        if (enforceStep.nextStepId || enforceStep.isBranch === "Y" || !enforceStep.stepId) {
          wx.showToast({ title: '请选择下一步骤', icon: 'none', duration: 800 });
          return;
        }
      }
    }



    
  },
  formReset: function () {
    console.log('form发生了reset事件')
  },
  bindPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e)
    this.setData({
      nextStepIndex: e.detail.value
    })
  },
  // configTypeChange: function (e) {
  //   // console.log('picker发送选择改变，携带值为', e)
  //   this.setData({
  //     configType: e.detail.value
  //   })
  // },
  bindbreakReasonsChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e)
    this.setData({
      breakReasonsIndex: e.detail.value,
      breakReasonsDesc: this.data.breakReasons[e.detail.value].breakReasonName
    })
  },
  bindbreakReasonsDescChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      breakReasonsDesc: e.detail.value
    })
  },
  breakTypeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      breakTypeIndex: e.detail.value
    })
  },
  stepDescChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)
    this.setData({
      stepDesc: e.detail.value
    })
  },
  saveStepDesc: function () {
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('post', "enforceCurrInfos/saveStepDesc", {
      caseId: app.globalData.caseDetailData.caseId,
      stepDesc: this.data.stepDesc
    }, (res) => {
      console.log(res);
      wx.hideLoading()
      if (res.code == '00') {
        // _this.get_enforceCurrInfos()
        wx.showToast({ title: res.msg, icon: 'success' })
      } else {
        wx.showToast({ title: res.msg, icon: 'none' })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("接口错误=", res)
    });
  },
  close: function () {
    this.setData({ modalClose: true })
  },
  close_finishs: function () {
    this.setData({ modalClose: false })
  },
  over: function () {
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('put', "enforceCurrInfos/backCases", { caseId: app.globalData.caseDetailData.caseId }, (res) => {
      console.log(res);
      wx.hideLoading()
      _this.setData({ modalClose: false })
      if (res.code == '00') {
        _this.get_enforceCurrInfos();
        _this.setData({ modalForInput: false });
        wx.showToast({ title: res.msg, icon: 'success' })
      } else {
        wx.showToast({ title: res.msg, icon: 'none' })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("接口错误=", res)
    });
  },
  finishs: function () {
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('put', "enforceCurrInfos/finishs", { caseId: app.globalData.caseDetailData.caseId }, (res) => {
      console.log(res);
      wx.hideLoading()
      _this.setData({ modalClose: false })
      if (res.code == '00') {
        _this.get_enforceCurrInfos();
        _this.setData({ modalForInput: false });
        wx.showToast({ title: res.msg, icon: 'success' })
      } else {
        wx.showToast({ title: res.msg, icon: 'none' })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("接口错误=", res)
    });
  },
  breakStep: function () {
    if (this.data.breakReasons.length>0){
      this.setData({ modalForInput: true })
    }
  },
  canclebreakStep: function () {
    this.setData({ modalForInput: false })
  },
  confirmbreakStep: function () {
    // this.setData({ modalForInput: true })
    if (this.data.breakReasonsIndex === 'none') {
      wx.showToast({ title: '请选择中断原因', icon: 'none', duration: 800 });
      return;
    }
    if (!this.data.breakReasonsDesc) {
      wx.showToast({ title: '请输入描述', icon: 'none', duration: 800 });
      return;
    }
    let sendData = {
      caseId: app.globalData.caseDetailData.caseId,
      breakReasonId: this.data.breakReasons[this.data.breakReasonsIndex].breakReasonId,
      autoRenewDays: this.data.breakReasons[this.data.breakReasonsIndex].autoRenewDays,
      breakReasonName: this.data.breakReasons[this.data.breakReasonsIndex].breakReasonName,
    }
    if (this.data.ROLE_BreakForEver) {
      sendData.breakType = this.data.breakTypes[this.data.breakTypeIndex].id
    } else {
      sendData.breakType='1';
    }
    console.log(sendData)
    let _this = this;
    wx.showLoading({ title: ' ', mask: true })
    request.requestMisApi('put', "enforceCurrInfos/breaks", sendData, (res) => {
      console.log(res);
      wx.hideLoading()
      if (res.code == '00') {
        _this.get_enforceCurrInfos();
        _this.setData({ modalForInput: false });
        wx.showToast({ title: res.msg, icon: 'success' })
      } else {
        wx.showToast({ title: res.msg, icon: 'none' })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("接口错误=", res)
    });
  },
  getstepDescValue: function (e) {
    this.setData({
      stepDesc: e.detail.value
    })
  },
  otherInputChange: function (e) {
    console.log(e)
    let otherInput = this.data.otherInput;
    if (e.currentTarget.dataset.datetype === 'date') {
      otherInput[e.currentTarget.dataset.index].value_date = e.detail.value
    } else if (e.currentTarget.dataset.datetype === 'time') {
      otherInput[e.currentTarget.dataset.index].value_time = e.detail.value
    } else {
      otherInput[e.currentTarget.dataset.index].value = e.detail.value
    }
    this.setData({
      otherInput: otherInput
    })
  },
  changeCurrent: function (e) {
    console.log('changeCurrent====', e)
    if (e.detail.source == "touch") {
      // this.setData({
      //   currentNum: e.detail.current
      // })
      if (e.detail.current == '1'){
        this.tab2();
      } else if (e.detail.current == '2'){
        this.tab3();
      }else{
        this.tab1();
      }
    }
  },
  tab1: function () {
    setTimeout(() => {
      this.setData({
        subZindex: 10
      })
    }, 100)
    this.setData({
      currentNum: 0
    })
  },
  tab2: function () {
    // console.log("详情==", JSON.stringify(this.data.enforceCurrInfos))
    let tempData = this.data.enforceCurrInfos;
    let docType = tempData.docType;
    if (docType) {
      docType = docType * 1 - 1;
    }
    this.setData({
      currentNum: 1,
      txtDate: util.dateStr(tempData.effectDate),
      defaultTxtType: docType
    })
  },
  tab3: function () {
    // console.log("案件进展列表=", JSON.stringify(this.data.enforceCurrInfos.enforceStepRecordWithBLOBs))
    let tempList = this.data.enforceCurrInfos.enforceStepRecordWithBLOBs;
    tempList.forEach(function (e) {
      let monthDate = util.timetrans(e.finishTime, "day");
      e.monthDate = monthDate.substring(5, 10)
      e.dayHM = util.timetrans(e.finishTime, "timeHM");
      e.openFile = false;
      if (e.enforceStepRecordDocs.length > 0) {
        let tempList = e.enforceStepRecordDocs;
        tempList.forEach(function (item) {
          let tempUrl = item.docUrl.replace("https://winhc.oss-cn-shanghai.aliyuncs.com/", '');
          item.docName = tempUrl.substring(10, tempUrl.length);
        });
        e.enforceStepRecordDocs = tempList;
      }
    });
    this.setData({
      currentNum: 2,
      enforceStepRecordWithBLOBs: tempList,
      tab3Flag:false
    })
  },

  //文本类型触发
  changeTxtType: function (e) {
    let value = e.detail.value;
    this.setData({
      defaultTxtType: value
    });
  },

  //文本生效时间
  txtDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      txtDate: e.detail.value
    })
  },

  //点击编辑或保存
  formDetSubmit: function (e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    if (this.data.showAble) {
      this.setData({
        showAble: false,
        editOrSave: "保存"
      });
    } else {
      //开始去调用保存API
      this.saveCaseDet(e.detail.value);
    }
  },


  //保存详情
  saveCaseDet: function (data) {
    let date = data.txtDate;
    let bodyInfo = {
      effectDate: date.replace(/-/g, ""),
      docType: data.defaultTxtType * 1 + 1,
      judgeName: data.judgeName,
      judgeLink: data.judgeLink,
      judgeOpenDate: data.judgeOpenDate,
      enforceCaseNo: data.enforceCaseNo,
      caseId: app.globalData.caseDetailData.caseId
    }
    let _that = this;
    console.log("bodyInfo==", bodyInfo)
    request.requestMisApi("PUT", "enforceCurrInfos", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("提交详情成功成功=", res)
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      })
      _that.setData({
        showAble: true,
        editOrSave: "编辑"
      });
    }, (res) => {
      console.log("提交详情失败=", res)
    });
  },


  //编辑撤销步骤
  //点击编辑
  edit: function (e) {
    let edit_item = e.currentTarget.dataset.info;
    // console.log(edit_item)
    if ((new Date().getTime() - edit_item.finishTime * 1) < 30 * 60 * 1000) {
      this.setData({ showEdit: true, edit_value: edit_item.recordText, editId: edit_item.id})
    }else{
      this.setData({
        newDateTime: new Date().getTime()
      });
    }
  },

  //点击删除
  del: function(e){
    let item = e.currentTarget.dataset.info;
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '是否确认撤销该记录',
      confirmColor:'#1b82d1',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({ title: '加载中', mask: true })
          request.requestMisApi('delete', "enforceStepRecords/" + item.id, {}, (res) => {
            console.log("成功=", res);
            wx.hideLoading()
            if (res.code == '00') {
              _this.setData({tab3Flag: true });
              _this.get_enforceCurrInfos();
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }, (res) => {
            wx.hideLoading()
            console.log("失败=", res)
          });
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

 //编辑保存
  edit_valueinput: function (e) {
    this.setData({
      edit_value: e.detail.value
    });
  },

  //编辑取消
  cancle: function (e) {
    this.setData({ showEdit: false })
  },
  //编辑确认
  confirm: function (e) {
    let edit_value = this.data.edit_value;
    if (!edit_value) {
      wx.showToast({
        title: '请输入描述',
        icon: 'none',
      })
      return;
    }
    let bodyInfo = {
      id: this.data.editId,
      recordText: edit_value
    };
    let _this = this;
    wx.showLoading({ title: '加载中', mask: true })
    request.requestMisApi('put', "enforceStepRecords", bodyInfo, (res) => {
      console.log("成功=", res);
      wx.hideLoading()
      if (res.code == '00') {
        _this.setData({ showEdit: false, tab3Flag:true});
        _this.get_enforceCurrInfos();
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      wx.hideLoading()
      console.log("失败=", res)
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //转发
  // onShareAppMessage: function (res) {
  //   if (res.from === 'button') {
  //     // 来自页面内转发按钮
  //     console.log("来自页面内的转发", res.target)
  //   }
  //   let This = this;
  //   return {
  //     title: "转发执行跟踪测试",
  //     path: 'pages/enforceDetail/enforceDetail?caseId=' + app.globalData.caseDetailData.caseId,

  //     success: function (res) {
  //       // 转发成功
  //       console.log("转发成功返回数据=", res)
  //       wx.showShareMenu({
  //         // 要求小程序返回分享目标信息
  //         withShareTicket: true
  //       });

  //       if (res.shareTickets) {
  //         // 获取转发详细信息
  //         wx.getShareInfo({
  //           shareTicket: res.shareTickets[0],
  //           success(res) {

  //           },
  //           fail() { },
  //           complete() { }
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     },
  //     complete: function () {

  //     }
  //   }
  // },
})
